package soar.template.springboot.share.utils;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.HttpsURLConnection;

public class HttpUtil
{
    public static String http(String method, String url_s, String params)
            throws Exception
    {
        if (params == null)
            params = "";

        HttpURLConnection conn;
        if (method.equals("GET"))
        {
            if (!params.isEmpty())
            {
                if (url_s.indexOf("?") == -1)
                    url_s += "?" + params;
                else
                    url_s += "&" + params;
            }
            URL url = new URL(url_s);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET"); // 不起作用，看DoOutput
        }
        else
        {
            URL url = new URL(url_s);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
        }

        set_url_connection_request(conn);
        conn.setConnectTimeout(5 * 1000);
        conn.setReadTimeout(10 * 1000);
        conn.connect();

        if (method.equals("GET"))
        {

        }
        else
        {
            byte[] b = params.getBytes();
            OutputStream out = conn.getOutputStream();
            out.write(b, 0, b.length);
            out.flush();
            out.close();
        }

        return read_url_connection_response(conn);
    }

    public static String https(String method, String url_s, String params)
            throws Exception
    {
        if (params == null)
            params = "";

        HttpsURLConnection conn;
        if (method.equals("GET"))
        {
            if (!params.isEmpty())
            {
                if (url_s.indexOf("?") == -1)
                    url_s += "?" + params;
                else
                    url_s += "&" + params;
            }
            URL url = new URL(url_s);
            conn = (HttpsURLConnection) url.openConnection();
            conn.setRequestMethod("GET"); // 不起作用，看DoOutput
        }
        else
        {
            URL url = new URL(url_s);
            conn = (HttpsURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
        }

        set_url_connection_request(conn);
        conn.setConnectTimeout(5 * 1000);
        conn.setReadTimeout(10 * 1000);
        conn.connect();

        if (method.equals("GET"))
        {

        }
        else
        {
            byte[] b = params.getBytes();
            OutputStream out = conn.getOutputStream();
            out.write(b, 0, b.length);
            out.flush();
            out.close();
        }

        return read_url_connection_response(conn);
    }

    private static void set_url_connection_request(HttpURLConnection conn)
    {
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
        conn.setRequestProperty("Content-type",
                "application/x-www-form-urlencoded; charset=utf-8");
        conn.setRequestProperty("Accept-Language",
                Locale.getDefault().toString());
        conn.setRequestProperty("Accept-Charset", "UTF-8");
    }

    private static String read_url_connection_response(HttpURLConnection conn)
            throws Exception
    {
        InputStream in = conn.getInputStream();
        int content_length = conn.getContentLength();
        if (content_length < 0)
            content_length = 10 * 1024 * 1024;
        byte[] buf = new byte[content_length];
        int size = 0;
        while (true)
        {
            int n = in.read(buf, size, content_length - size);
            if (n == -1)
                break;
            size += n;
        }
        // System.out.println("ContentLength: " + conn.getContentLength());
        // System.out.println("size: " + size);

        String charset = conn.getContentEncoding();
        if (charset == null)
        {
            String content_type = conn.getContentType();
            if (content_type != null)
            {
                Pattern pattern = Pattern
                        .compile(".*charset *= *([A-Za-z_\\-0-9]+).*");
                Matcher matcher = pattern.matcher(content_type);
                if (matcher.matches())
                {
                    charset = matcher.group(1);
                }
                else
                {
                    charset = "UTF-8";
                }
            }
            else
            {
                charset = "UTF-8";
            }
        }
        return new String(buf, 0, size, charset);
    }
}
